﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
//using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Threading.Tasks;
//using System.Windows.Shapes;
using System.IO;
using Finisar.SQLite;
using System.Data;
using sqlite;
using AForge.Imaging.Textures;
using AForge.Imaging.Filters;

namespace IBoLT
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
	{
		#region Поля

		// Имя конфигурационного файла
		private String configFileName = "config.ini";
		// Имя параметра выбраной БД
		private String boxSDB = "DB";
		// Возможные знаения для этого параметра (0 - локальная; 1 - глобальная)
		private String[] SDBValue = { "local", "global" };
		// Имя параметра вывода окна выбора БД
		private String boxDontAskSDB = "dontAsk";
		// Возможные знаения для этого параметра (0 - открывать; 1 - не открывать)
		private String[] dontAskValue = { "False", "True" };

		private String dbresPath = "dbresPath";
		// Путь куда сохраняются текстуры
		private String dbResultTextures = "Textures";
		// Путь к локальной базе и название файла с ней
		private String dbPath = "iboltLDB.db";

		// Выбранная БД
		private string resultDB;

		// Цветовой режим текстуры
		private int colorMode;

		// Резмеры предпросмотра в генераторах и фильрах
		private int widthPreTexture = 200;
		private int heightPreTexture = 200;

		// Объект с создаваемой текстурой и её настройками
		TextureSettings STexture;

		// Индентификатор, открыто ли полотно (для активности некоторых команд меню "файл" и "генераторы")
		private static bool isOpenCanvas = false;
		// Индентификатор, создана ли текстура в цветах RGB (для активности некоторых команд меню "фильтры" и "коррекция")
		private static bool isExistsTextureRGB = false;
		// Индентификатор, создана ли текстура в оттенках серого (для активности некоторых команд меню "фильтры" и "коррекция")
		private static bool isExistsTextureGS = false;

		#endregion

		#region Свойства

		public static bool IsOpenCanvas
		{	get { return isOpenCanvas; }
			set	{ isOpenCanvas = value; } }
		public static bool IsExistsTextureRGB
		{	get { return isExistsTextureRGB; }
			set { isExistsTextureRGB = value; } }
		public static bool IsExistsTextureGS
		{	get { return isExistsTextureGS; }
			set { isExistsTextureGS = value; } }
		
		#endregion

		// Конструктор

		public MainWindow()
		{
			System.Reflection.Assembly a = System.Reflection.Assembly.GetEntryAssembly();
			string baseDir = System.IO.Path.GetDirectoryName(a.Location);
			dbResultTextures = baseDir + "\\" + dbResultTextures;

			InitializeComponent();

			// Добавление привязок команд
			fCommandBinding();

			if (System.IO.File.Exists(configFileName))
			{
				dbResultTextures = ConfigFile.fReturnValue(configFileName, dbresPath);

				// Проверяем, необходимо ли ещё раз вывести окно выбора БД
				if (ConfigFile.fIsExistValue(configFileName, boxDontAskSDB, dontAskValue[0]))
					CommandsIBoLT.cSelectDB.Execute(null, this);
				// Из конфигурационного файла получаем выбранную БД
				else
				{
					if (ConfigFile.fReturnValue(configFileName, boxSDB) == SDBValue[0].ToLower())
						resultDB = SDBValue[0];
					else if (ConfigFile.fReturnValue(configFileName, boxSDB) == SDBValue[1].ToLower())
						resultDB = SDBValue[1];
					else
						CommandsIBoLT.cSelectDB.Execute(null, this);
				}
			}
			else
				CommandsIBoLT.cSelectDB.Execute(null, this);
		}

		
		// Привязка команд к обработчикам //

		#region Привязка команд

		private void fCommandBinding()
		{
			CommandBinding commBind;

// Файл /////////////////////////////////////////////////////////////////////////////
			commBind = new CommandBinding(ApplicationCommands.New, hNewEx, hNewCEx);			this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cReviewDB, hReviewDBEx);				this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(NavigationCommands.Search, hSearchEx);				this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(ApplicationCommands.Close, hCloseEx, hCloseCEx);		this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(ApplicationCommands.Save, hSaveEx, hSaveCEx);			this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(ApplicationCommands.SaveAs, hSaveAsEx, hSaveAsCEx);	this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(ApplicationCommands.Print, hPrintEx, hPrintCEx);		this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cExit, hExitEx);						this.CommandBindings.Add(commBind);
/////////////////////////////////////////////////////////////////////////////////////

// Генераторы ///////////////////////////////////////////////////////////////////////
			commBind = new CommandBinding(CommandsIBoLT.cTree, hTreeEx, hTreeCEx);						this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cLeaves, hLeavesEx, hLeavesCEx);				this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cMandelbrot, hMandelbrotEx, hMandelbrotCEx);	this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cCellular, hCellularEx, hCellularCEx);			this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cPerlinNoise, hPerlinNoiseEx, hPerlinNoiseCEx); this.CommandBindings.Add(commBind);
/////////////////////////////////////////////////////////////////////////////////////

// Фильтры //////////////////////////////////////////////////////////////////////////
			commBind = new CommandBinding(CommandsIBoLT.cRotateChannelsRGB, hRotateChannelsRGBEx, hRotateChannelsRGBCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cChannelFilteringRGB, hChannelFilteringRGBEx, hChannelFilteringRGBCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cExtractChannelRGB, hExtractChannelRGBEx, hExtractChannelRGBCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cRotateChannelsYCbCr, hRotateChannelsYCbCrEx, hRotateChannelsYCbCrCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cChannelFilteringYCbCr, hChannelFilteringYCbCrEx, hChannelFilteringYCbCrCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cExtractChannelYCbCr, hExtractChannelYCbCrEx, hExtractChannelYCbCrCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cWave, hWaveEx, hWaveCEx);			this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cJitter, hJitterEx, hJitterCEx);	this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cOilPainting, hOilPaintingEx, hOilPaintingCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cMosaic, hMosaicEx, hMosaicCEx);	this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cPosterization, hPosterizationEx, hPosterizationCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cAdditiveNoise, hAdditiveNoiseEx, hAdditiveNoiseCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cSAPNoise, hSAPNoiseEx, hSAPNoiseCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cSmoothing, hSmoothingEx, hSmoothingCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cSepia, hSepiaEx, hSepiaCEx);		this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cOurFilter, hOurFilterEx, hOurFilterCEx);
																							this.CommandBindings.Add(commBind);
/////////////////////////////////////////////////////////////////////////////////////

// Коррекция ////////////////////////////////////////////////////////////////////////
			commBind = new CommandBinding(CommandsIBoLT.cArbitrarily, hArbitrarilyEx, hArbitrarilyCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cMirrorHorizontal, hMirrorHorizontalEx, hMirrorHorizontalCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cMirrorVertical, hMirrorVerticalEx, hMirrorVerticalCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cColor, hColorEx, hColorCEx);		this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cBinarization, hBinarizationEx, hBinarizationCEx);
																							this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cInvert, hInvertEx, hInvertCEx);	this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cBrightnessAContrast, hBrightnessAContrastEx, hBrightnessAContrastCEx);
																							this.CommandBindings.Add(commBind);
/////////////////////////////////////////////////////////////////////////////////////

// Настройки ////////////////////////////////////////////////////////////////////////
			commBind = new CommandBinding(CommandsIBoLT.cSelectDB, hSelectDBEx);	this.CommandBindings.Add(commBind);
/////////////////////////////////////////////////////////////////////////////////////
			
// Справка //////////////////////////////////////////////////////////////////////////
			commBind = new CommandBinding(ApplicationCommands.Help, hHelpEx);		this.CommandBindings.Add(commBind);
			commBind = new CommandBinding(CommandsIBoLT.cAbout, hAboutEx);			this.CommandBindings.Add(commBind);
/////////////////////////////////////////////////////////////////////////////////////
		}

		#endregion

		// Обработчики //

		#region Файл

		// Обработчик кнопки "Создать"
		private void hNewEx(object sender, ExecutedRoutedEventArgs e)
		{
			SettingWindows.NewTexture settingsWindow = new SettingWindows.NewTexture();
			settingsWindow.ShowDialog();

			if (settingsWindow.DialogResult.Value)
			{
				int width = settingsWindow.width;
				int height = settingsWindow.height;

				wTexture.Width = width;
				wTexture.Height = height;

				Double coef = (Double)Math.Max(width, height) / (Double)Math.Max(widthPreTexture, heightPreTexture);
				widthPreTexture = (int)(width / coef);
				heightPreTexture = (int)(height / coef);

				colorMode = settingsWindow.color;

				STexture = new TextureSettings(settingsWindow.name, 
					new System.Drawing.Bitmap(settingsWindow.width, settingsWindow.height, System.Drawing.Imaging.PixelFormat.Format24bppRgb));

				// Заливаю битмап белым цветом
				//Parallel.For(0, widthTexture, i =>
				System.Drawing.Imaging.BitmapData ImageData = IBoLT.SystemDrawingHelper.LockImage(STexture.Texture);
				int ImagePixelSize = IBoLT.SystemDrawingHelper.GetPixelSize(ImageData);

				for (int i = 0; i < STexture.Width; ++i)
				{
					for (int j = 0; j < STexture.Height; ++j)
					{
						IBoLT.SystemDrawingHelper.SetPixel(ImageData, i, j, System.Drawing.Color.White, ImagePixelSize);
					}
				}//);

				IBoLT.SystemDrawingHelper.UnlockImage(STexture.Texture, ImageData);

				wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
				wTexture.Visibility = Visibility.Visible;
			}
		}
		private void hNewCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = !isOpenCanvas; }

		// Обработчик кнопки "Обзор базы"
		private void hReviewDBEx(object sender, ExecutedRoutedEventArgs e)
		{
            SettingWindows.tdLBase settingsWindow = new SettingWindows.tdLBase(dbPath);
            settingsWindow.ShowDialog();
		}

		// Обработчик кнопки "Поиск по базе"
		private void hSearchEx(object sender, ExecutedRoutedEventArgs e)
		{

		}

		// Обработчик кнопки "Закрыть"
		private void hCloseEx(object sender, ExecutedRoutedEventArgs e)
		{
			isOpenCanvas = false;
			wTexture.Visibility = Visibility.Hidden;
		}
		private void hCloseCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isOpenCanvas; }

		// Обработчик кнопки "Сохранить"
		private void hSaveEx(object sender, ExecutedRoutedEventArgs e)
		{
			if (resultDB == SDBValue[0])
			{
				//устанавливаем пути сохранения
				string configpath = ConfigFile.fReturnValue(configFileName, dbResultTextures);
				if (!Directory.Exists(configpath))
					Directory.CreateDirectory(configpath);

				//System.Reflection.Assembly a = System.Reflection.Assembly.GetEntryAssembly();
				//string baseDir = System.IO.Path.GetDirectoryName(a.Location);
				string path = configpath + "\\" + STexture.NameTexture + ".bmp";
				//устанавливаем пути сохранения

				//устанавливаем все необходимые переменные работы с базой
				sqliteclass mydb = new sqliteclass();// Класс  работы с БД
				DataTable datarows = null;// Класс  работы с БД
				string sSql = string.Empty; // Строка запроса
				//устанавливаем все необходимое для работы с базой

				//Вычисляем индекс изображения
				IBoLT.HelperClasses.WMetrics metric = new HelperClasses.WMetrics(STexture.Texture);
				//Вычисляем индекс изображения

				//Инициализируем переменные для сохранения в базу
				string id_user = "Alexander";
				string id_attribute = string.Empty;
				string searchInfo = metric.CWMetric().ToString();
				string description = "Процедурная текстура";
				string settingsXML = STexture.Settings.ToString();
				//Инициализируем переменные для сохранения в базу

				STexture.Texture.Save(path, System.Drawing.Imaging.ImageFormat.Bmp);

				/////Запись АТРИБУТОВ в базу
				sSql = @"INSERT INTO tAttributes (id_method,id_type,arguments) values(1,1,'" + settingsXML + "');";
				if (mydb.iExecuteNonQuery(dbPath, sSql, 1) == 0)
				{
					MessageBox.Show("Ошибка записи в таблицу атрибутов!");
				}
				/////Получение последнего индекса из таблицы атрибутов
				sSql = @"SELECT id_attribute  FROM  tAttributes";
				datarows = mydb.drExecuteAsDataTable(dbPath, sSql);
				id_attribute = datarows.Rows[datarows.Rows.Count - 1][0].ToString();
				/////Запись ТЕКСТУР в базу
				sSql = @"INSERT INTO tTextures (id_user,id_attribute,searchInfo,nameTexture,path,description) VALUES('"
																													+ id_user + "'," +
																													id_attribute + "," +
																													"'" + searchInfo + "'," +
																													"'" + STexture.NameTexture + "'," +
																													"'" + path + "'," +
																													"'" + description + "');";
				if (mydb.iExecuteNonQuery(dbPath, sSql, 1) == 0)
				{
					MessageBox.Show("Ошибка записи в таблицу текстур!");
				}
			}
			else if (resultDB == SDBValue[1])
			{
				MessageBox.Show("Не удалось подключиться к глобальной базе данных.");
			}
		}
		private void hSaveCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isOpenCanvas; }

		// Обработчик кнопки "Сохранить как"
		private void hSaveAsEx(object sender, ExecutedRoutedEventArgs e)
		{
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();

            dlg.DefaultExt = ".bmp";
            dlg.Filter = "24-разрядный рисунок (.bmp)|*.bmp";
            dlg.Title = "Сохранение текстуры";
            dlg.FileName = STexture.NameTexture;

            if (dlg.ShowDialog().Value)
            {
                STexture.Texture.Save(dlg.FileName, System.Drawing.Imaging.ImageFormat.Bmp);

                dlg.DefaultExt = ".xml";
                dlg.Filter = "XML-документ (.xml)|*.xml";
                dlg.Title = "Сохранение параметров текстуры";
                dlg.FileName = STexture.NameTexture;

                if (dlg.ShowDialog().Value)
                {
                    STexture.SaveSettingsToFile(dlg.FileName);
                }
            }
		}
		private void hSaveAsCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isOpenCanvas; }

		// Обработчик кнопки "Печать"
		private void hPrintEx(object sender, ExecutedRoutedEventArgs e)
		{

		}
		private void hPrintCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isOpenCanvas; }

		// Обработчик кнопки "Выход"
		private void hExitEx(object sender, ExecutedRoutedEventArgs e)
		{
			ApplicationCommands.Close.Execute(null, this);
			this.Close();
		}

		#endregion

		#region Генераторы

		// Обработчик кнопки "Дерево"
		private void hTreeEx(object sender, ExecutedRoutedEventArgs e)
		{
			ResizeNearestNeighbor minTextur = new ResizeNearestNeighbor(widthPreTexture, heightPreTexture);
			SettingWindows.Tree settingsWindow = new SettingWindows.Tree(minTextur.Apply(STexture.Texture), STexture);
			settingsWindow.ShowDialog();

			if (settingsWindow.DialogResult.Value)
			{
				STexture = settingsWindow.STexture;
				Fractals.FractalTree fractal = settingsWindow.fractal;

				fractal.Texture = STexture.Texture;
				STexture.Texture = fractal.ToBitmap();

				wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);

				if (colorMode == 0)
				{
					isExistsTextureRGB = true;
				}
				else
				{
					isExistsTextureGS = true;
				}
			}
		}
		private void hTreeCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isOpenCanvas; }

		// Обработчик кнопки "Листья"
		private void hLeavesEx(object sender, ExecutedRoutedEventArgs e)
		{
			ResizeNearestNeighbor minTextur = new ResizeNearestNeighbor(widthPreTexture, heightPreTexture);
			SettingWindows.Leaves settingsWindow = new SettingWindows.Leaves(minTextur.Apply(STexture.Texture), STexture);
			settingsWindow.ShowDialog();

			if (settingsWindow.DialogResult.Value)
			{
				STexture = settingsWindow.STexture;
				Fractals.Leaves fractal = settingsWindow.fractal;

				fractal.Texture = STexture.Texture;
				STexture.Texture = fractal.Calculate();

				wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);

				if (colorMode == 0)
				{
					isExistsTextureRGB = true;
				}
				else
				{
					isExistsTextureGS = true;
				}
			}
		}
		private void hLeavesCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isOpenCanvas; }

		// Обработчик кнопки "Мандельброт"
		private void hMandelbrotEx(object sender, ExecutedRoutedEventArgs e)
		{
			ResizeNearestNeighbor minTextur = new ResizeNearestNeighbor(widthPreTexture, heightPreTexture);
			SettingWindows.Mandelbrot settingsWindow = new SettingWindows.Mandelbrot(minTextur.Apply(STexture.Texture), STexture);
			settingsWindow.ShowDialog();

			if (settingsWindow.DialogResult.Value)
			{
				STexture = settingsWindow.STexture;
				Fractals.AlgebraicFractals fractal = settingsWindow.fractal;

				fractal.Texture = STexture.Texture;
				fractal.Calculate();
				STexture.Texture = fractal.ToBitmap();

				wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);

				if (colorMode == 0)
				{
					isExistsTextureRGB = true;
				}
				else
				{
					isExistsTextureGS = true;
				}
			}
		}
		private void hMandelbrotCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isOpenCanvas; }

		// Обработчик кнопки "Клеточная текстура"
		private void hCellularEx(object sender, ExecutedRoutedEventArgs e)
		{
			ResizeNearestNeighbor minTextur = new ResizeNearestNeighbor(widthPreTexture, heightPreTexture);
			SettingWindows.Cellular settingsWindow = new SettingWindows.Cellular(minTextur.Apply(STexture.Texture), STexture);
			settingsWindow.ShowDialog();

			if (settingsWindow.DialogResult.Value)
			{
				STexture = settingsWindow.STexture;
				Cellular.CellularTexture generator = settingsWindow.generator;

				generator.Texture = STexture.Texture;
				generator.CalculateDistance();
				STexture.Texture = generator.ToBitmap();

				wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);

				if (colorMode == 0)
				{
					isExistsTextureRGB = true;
				}
				else
				{
					isExistsTextureGS = true;
				}
			}
		}
		private void hCellularCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isOpenCanvas; }

		// Обработчик кнопки "Шум Перлина"
		private void hPerlinNoiseEx(object sender, ExecutedRoutedEventArgs e)
		{
			ResizeNearestNeighbor minTextur = new ResizeNearestNeighbor(widthPreTexture, heightPreTexture);
			SettingWindows.PerlinNoise settingsWindow = new SettingWindows.PerlinNoise(minTextur.Apply(STexture.Texture), STexture);
			settingsWindow.ShowDialog();

			if (settingsWindow.DialogResult.Value)
			{
				STexture = settingsWindow.STexture;
				STexture.Texture = settingsWindow.filter.Apply(STexture.Texture);
				wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);

				if (colorMode == 0)
				{
					isExistsTextureRGB = true;
				}
				else
				{
					isExistsTextureGS = true;
				}
			}
		}
		private void hPerlinNoiseCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isOpenCanvas; }

		#endregion

		#region Фильтры

		// Обработчик кнопки "Вращение каналов" (RGB)
		private void hRotateChannelsRGBEx(object sender, ExecutedRoutedEventArgs e)
		{
			RotateChannels filter = new RotateChannels();
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hRotateChannelsRGBCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB; }

		// Обработчик кнопки "Канальный фильтр" (RGB)
		private void hChannelFilteringRGBEx(object sender, ExecutedRoutedEventArgs e)
		{
			ChannelFiltering filter = new ChannelFiltering();
			filter.Red = new AForge.IntRange(0, 255);
			filter.Green = new AForge.IntRange(0, 255);
			filter.Blue = new AForge.IntRange(0, 255);
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hChannelFilteringRGBCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB; }

		// Обработчик кнопки "Вырезка канала" (RGB)
		private void hExtractChannelRGBEx(object sender, ExecutedRoutedEventArgs e)
		{
			ExtractChannel filter = new ExtractChannel(AForge.Imaging.RGB.R);
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);

			isExistsTextureRGB = false;
			isExistsTextureGS = true;
		}
		private void hExtractChannelRGBCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB; }

		// Обработчик кнопки "Вращение каналов" (YCbCr)
		private void hRotateChannelsYCbCrEx(object sender, ExecutedRoutedEventArgs e)
		{

		}
		private void hRotateChannelsYCbCrCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB; }

		// Обработчик кнопки "Канальный фильтр" (YCbCr)
		private void hChannelFilteringYCbCrEx(object sender, ExecutedRoutedEventArgs e)
		{
			YCbCrFiltering filter = new YCbCrFiltering();
			filter.Y = new AForge.DoubleRange(0.5, 1);
			filter.Cb = new AForge.DoubleRange(-0.2, 0);
			filter.Cr = new AForge.DoubleRange(0.26, 0.5);
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hChannelFilteringYCbCrCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB; }

		// Обработчик кнопки "Вырезка канала" (YCbCr)
		private void hExtractChannelYCbCrEx(object sender, ExecutedRoutedEventArgs e)
		{
			isExistsTextureGS = true;
			isExistsTextureRGB = false;

			YCbCrExtractChannel filter = new YCbCrExtractChannel(AForge.Imaging.YCbCr.YIndex);
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hExtractChannelYCbCrCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB; }

		// Обработчик кнопки "Волна"
		private void hWaveEx(object sender, ExecutedRoutedEventArgs e)
		{
			ResizeBicubic minTextur = new ResizeBicubic(widthPreTexture, heightPreTexture);
			SettingWindows.Wave settingsWindow = new SettingWindows.Wave(minTextur.Apply(STexture.Texture), STexture);
			settingsWindow.ShowDialog();

			if (settingsWindow.DialogResult.Value)
			{
				STexture = settingsWindow.STexture;
				WaterWave filter = settingsWindow.filter;

				STexture.Texture = filter.Apply(STexture.Texture);
				wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
			}
		}
		private void hWaveCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }

		// Обработчик кнопки "Дрожание"
		private void hJitterEx(object sender, ExecutedRoutedEventArgs e)
		{
			ResizeBicubic minTextur = new ResizeBicubic(widthPreTexture, heightPreTexture);
			SettingWindows.Jitter window = new SettingWindows.Jitter(minTextur.Apply(STexture.Texture));
			window.ShowDialog();

			if (window.DialogResult.Value)
			{
				Jitter filter = new Jitter(5);

				STexture.Texture = filter.Apply(STexture.Texture);
				wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
			}
		}
		private void hJitterCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }

		// Обработчик кнопки "Масляная живопись"
		private void hOilPaintingEx(object sender, ExecutedRoutedEventArgs e)
		{
			ResizeBicubic minTextur = new ResizeBicubic(widthPreTexture, heightPreTexture);
			SettingWindows.OilPainting settingsWindow = new SettingWindows.OilPainting(minTextur.Apply(STexture.Texture));
			settingsWindow.ShowDialog();

			if (settingsWindow.DialogResult.Value)
			{
				OilPainting filter = new OilPainting(settingsWindow.brushSize);
				STexture.Texture = filter.Apply(STexture.Texture);
				wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
			}
		}
		private void hOilPaintingCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }

		// Обработчик кнопки "Мозаика"
		private void hMosaicEx(object sender, ExecutedRoutedEventArgs e)
		{
			ResizeBicubic minTextur = new ResizeBicubic(widthPreTexture, heightPreTexture);
			SettingWindows.Mosaic settingsWindow = new SettingWindows.Mosaic(minTextur.Apply(STexture.Texture));
			settingsWindow.ShowDialog();

			if (settingsWindow.DialogResult.Value)
			{
				if (settingsWindow.mType == 0)
				{
					Pixellate filter = new Pixellate(settingsWindow.mSize);
					STexture.Texture = filter.Apply(STexture.Texture);
				}
				else if (settingsWindow.mType == 1)
				{
					Pixellate filter = new Pixellate(settingsWindow.mWidth, settingsWindow.mHeight);
					STexture.Texture = filter.Apply(STexture.Texture);

				}
				else if (settingsWindow.mType == 2)
				{
					AForge.IntPoint[,] warpMap = new AForge.IntPoint[STexture.Height, STexture.Width];

					int size = settingsWindow.mSize;
					int maxOffset = -size + 1;

					for (int y = 0; y < STexture.Height; ++y)
					{
						for (int x = 0; x < STexture.Width; ++x)
						{
							int dx = (x / size) * size - x;
							int dy = (y / size) * size - y;

							if (dx + dy <= maxOffset)
							{
								dx = (x / size + 1) * size - 1 - x;
							}

							warpMap[y, x] = new AForge.IntPoint(dx, dy);
						}
					}

					ImageWarp filter = new ImageWarp(warpMap);
					STexture.Texture = filter.Apply(STexture.Texture);
				}
				wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
			}
		}
		private void hMosaicCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }

		// Обработчик кнопки "Постеризация"
		private void hPosterizationEx(object sender, ExecutedRoutedEventArgs e)
		{
			SimplePosterization filter = new SimplePosterization();
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hPosterizationCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }

		// Обработчик кнопки "Аддитивный шум"
		private void hAdditiveNoiseEx(object sender, ExecutedRoutedEventArgs e)
		{
			AForge.Math.Random.IRandomNumberGenerator randGenerator = new AForge.Math.Random.UniformGenerator(new AForge.DoubleRange(-100, 50));
			
			AdditiveNoise filter = new AdditiveNoise();
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hAdditiveNoiseCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }

		// Обработчик кнопки "Соль и перец"
		private void hSAPNoiseEx(object sender, ExecutedRoutedEventArgs e)
		{
			SaltAndPepperNoise filter = new SaltAndPepperNoise(15);
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hSAPNoiseCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }

		// Обработчик кнопки "Сглаживание"
		private void hSmoothingEx(object sender, ExecutedRoutedEventArgs e)
		{
			SettingWindows.Smooting settingsWindow = new SettingWindows.Smooting();
			settingsWindow.ShowDialog();
		}
		private void hSmoothingCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB; }

		// Обработчик кнопки "Сепия"
		private void hSepiaEx(object sender, ExecutedRoutedEventArgs e)
		{
			Sepia filter = new Sepia();
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hSepiaCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB; }

		// Обработчик кнопки "Свой пространственный фильтр"
		private void hOurFilterEx(object sender, ExecutedRoutedEventArgs e)
		{

		}
		private void hOurFilterCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB; }

		#endregion

		#region Коррекция

		// Обработчик кнопки "Произвольно"
		private void hArbitrarilyEx(object sender, ExecutedRoutedEventArgs e)
		{

		}
		private void hArbitrarilyCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }

		// Обработчик кнопки "Отразить по горизонтали"
		private void hMirrorHorizontalEx(object sender, ExecutedRoutedEventArgs e)
		{
			Mirror filter = new Mirror(false, true);
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hMirrorHorizontalCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }
		
		// Обработчик кнопки "Отразить по вертикали"
		private void hMirrorVerticalEx(object sender, ExecutedRoutedEventArgs e)
		{
			Mirror filter = new Mirror(true, false);
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hMirrorVerticalCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }
		
		// Обработчик кнопки "Цвет"
		private void hColorEx(object sender, ExecutedRoutedEventArgs e)
		{
			GrayscaleToRGB filter = new GrayscaleToRGB();
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);

			isExistsTextureGS = false;
			isExistsTextureRGB = true;
		}
		private void hColorCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureGS; }
		
		// Обработчик кнопки "Бинаризация"
		private void hBinarizationEx(object sender, ExecutedRoutedEventArgs e)
		{
			Threshold filter = new Threshold(100);
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hBinarizationCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureGS; }

		// Обработчик кнопки "Инвертирование"
		private void hInvertEx(object sender, ExecutedRoutedEventArgs e)
		{
			Invert filter = new Invert();
			STexture.Texture = filter.Apply(STexture.Texture);
			wTexture.Source = SystemDrawingHelper.BitmapToBitmapImage(STexture.Texture);
		}
		private void hInvertCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }

		// Обработчик кнопки "Яркость/Контрастность"
		private void hBrightnessAContrastEx(object sender, ExecutedRoutedEventArgs e)
		{

		}
		private void hBrightnessAContrastCEx(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isExistsTextureRGB || isExistsTextureGS; }

		#endregion

		#region Настройки

		// Обработчик кнопки "База данных"
		private void hSelectDBEx(object sender, ExecutedRoutedEventArgs e)
		{
			SettingWindows.SelectDB wSelectDB = new SettingWindows.SelectDB(configFileName, boxSDB, SDBValue, boxDontAskSDB, dontAskValue, dbresPath, dbResultTextures);
			wSelectDB.ShowDialog();

			if (wSelectDB.DialogResult.Value)
				resultDB = wSelectDB.resultDB;
		}

		#endregion

		#region Справка

		// Обработчик кнопки "Справка"
		private void hHelpEx(object sender, ExecutedRoutedEventArgs e)
		{

		}

		// Обработчик кнопки "О программе IBoLT"
		private void hAboutEx(object sender, ExecutedRoutedEventArgs e)
		{
			SettingWindows.About settingsWindow = new SettingWindows.About();
			settingsWindow.ShowDialog();
		}

		#endregion
	}
}
